﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZBJF.Warranty.WeiXin;
using Senparc.Weixin;
using ZBJF.Warranty.Common.Common;
using Newtonsoft.Json;
using Senparc.Weixin.MP.MvcExtension;
using Senparc.Weixin.MP.Entities.Request;
using ZBJF.Warranty.BLL.Cached;

namespace ZBJF.Warranty.H5.Controllers
{
    public class WeiXinController : Controller
    {
        #region 微信tocken验证 + ActionResult Get(string signature, string timestamp, string nonce, string echostr)
        /// <summary>
        /// 微信tocken验证
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("Index")]
        [LoginFilter(IsCheck = false)]
        public ActionResult Get(string signature, string timestamp, string nonce, string echostr)
        {
            LogHelper.WriteLog(string.Format("微信tocken验证 : signature:{0},timestamp:{1},nonce:{2},echostr:{3}", signature, timestamp, nonce, echostr), LogType.tag);
            if (WeiXinHelper.CheckToken(signature, timestamp, nonce))
            {
                return Content(echostr);//返回随机字符串则表示验证通过
            }
            else
            {
                LogHelper.WriteLog(string.Format("微信tocken验证失败: signature:{0},timestamp:{1},nonce:{2},echostr:{3}", signature, timestamp, nonce, echostr), LogType.tag);
                return View();
            }
        }
        #endregion

        #region 微信消息/事件 + ActionResult Post(PostModel model)
        /// <summary>
        /// 微信消息/事件
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("Index")]
        [LoginFilter(IsCheck = false)]
        public ActionResult Post(PostModel model)
        {
            if (!WeiXinHelper.CheckToken(model.Signature, model.Timestamp, model.Nonce))
            {
                return Content("参数错误！");
            }

            //设置每个人上下文消息储存的最大数量，防止内存占用过多，如果该参数小于等于0，则不限制
            int maxRecordCount = 5;

            PostModel postModel = new PostModel();
            postModel.AppId = WeiXinConfig.APPID;
            postModel.EncodingAESKey = WeiXinConfig.EncodingAESKey;
            postModel.Token = WeiXinConfig.Token;
            //自定义MessageHandler，对微信请求的详细判断操作都在这里面。
            var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount);

            messageHandler.OmitRepeatedMessage = true;//启用消息去重功能

            messageHandler.Execute();//执行微信处理过程
            string responseContent = messageHandler.ResponseDocument.ToString();

            return new FixWeixinBugWeixinResult(messageHandler);
        }
        #endregion

        #region 微信登录(用户授权) + ActionResult WxLogin()
        /// <summary>
        /// 微信登录(用户授权)
        /// </summary>
        /// <returns></returns>
        [LoginFilter(IsCheck = false)]
        public ActionResult WxLogin()
        {
            string domain = System.Web.HttpContext.Current.Request.Url.Host;
            Session["BackUrl"] = HttpUtility.UrlDecode(System.Web.HttpContext.Current.Request["backUrl"]);//夸控制器无法取到Session的值
            var weixinurl = WeiXinHelper.GetAuthorizeUrl("", "http://" + domain + "/WeiXin/WxLoginPageCallback", Senparc.Weixin.MP.OAuthScope.snsapi_base);
            return Redirect(weixinurl);
        }
        #endregion

        #region 登录回来的回发 + ActionResult WxLoginPageCallback(string code, string state)
        /// <summary>
        /// 登录回来的回发
        /// </summary>
        /// <returns></returns>
        [LoginFilter(IsCheck = false)]
        public ActionResult WxLoginPageCallback(string code, string state)
        {
            LogHelper.WriteLog("用户授权（WxLoginPageCallback）回调；code:" + code + ";state:" + state, LogType.tag);
            if (string.IsNullOrEmpty(code))
            {
                //===================================用户拒绝授权 或 出现异常
            }

            //获取微信用户信息
            var userInfo = WeiXinHelper.GetWeiXinUserInfo(code);
            LogHelper.WriteLog("用户授权（WxLoginPageCallback）获取用户信息；用户信息:" + JsonConvert.SerializeObject(userInfo), LogType.tag);

            if (userInfo == null || userInfo.errcode != ReturnCode.请求成功)
            {
                //===================================获取失败
                LogHelper.WriteLog("用户授权（WxLoginPageCallback）获取用户信息失败；用户信息:" + JsonConvert.SerializeObject(userInfo), LogType.tag);
            }


            if (!string.IsNullOrEmpty(userInfo.openid))
            {
                string openId = userInfo.openid;
                Session["OpenId"] = openId;
                //=========跳转至用户在验证之前进入的页面，可以事先缓存
                object sessionBackUrl = Session["BackUrl"];
                string backUrl = null;
                if (sessionBackUrl != null)
                {
                    backUrl = sessionBackUrl.ToString();
                    Session.Remove("BackUrl");
                }
                else
                {
                    backUrl = System.Web.HttpContext.Current.Request.Url.Host;
                }
                return Redirect(backUrl);
            }
            else
            {
                LogHelper.WriteLog("用户授权（WxLoginPageCallback）OpenId不存在；用户信息:" + JsonConvert.SerializeObject(userInfo), LogType.tag);
                return Redirect("/Erro/Index");
            }
        }
        #endregion

        #region 获取分享朋友、朋友圈信息 + ActionResult GetShareConfig(string url)
        /// <summary>
        /// 获取分享朋友、朋友圈信息
        /// </summary>
        /// <returns></returns>
        [LoginFilter(IsCheck = false)]
        public ActionResult GetShareConfig(string url)
        {
            if (!CommonMethod.IsRequestFormWeiXin(Request.UserAgent))
                return Json(string.Empty, JsonRequestBehavior.AllowGet);
            return Json(JsApiHelper.GetJsSdkUiPackage(url), JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}